﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Top.Web;
using Top.Web.Api;
using Top.Web.Api.Filters;
using Top.PointStore.Business;
using Top.PointStore.Web.Filters;
//using Top.PointStore.Filters;

namespace Top.PointStore.Controllers
{
    /// <summary>
    /// 兑换规则
    /// </summary>
    [Provider]
    public class ExchangeRuleController : ApiBase
    {
        /// <summary>保存兑换规则
        /// </summary>
        /// <param name="productKid">商品id</param>
        /// <param name="pointNum">积分</param>
        /// <param name="beginTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="kid">兑换规则id</param>
        /// <param name="disabled"></param>
        /// <returns></returns>
        [Login]
        public async Task<object> Save(int productKid, int pointNum, DateTime? beginTime = null, DateTime? endTime = null, int? kid = null, bool? disabled = null)
        {
            var begin = beginTime ?? DateTime.Now;
            var end = endTime ?? DateTime.Now.AddDays(30);

            T_ExchangeRuleExpand model = new T_ExchangeRuleExpand();
            model.F_ProductKid = productKid;
            model.F_BeginTime = begin;
            model.F_EndTime = end;
            model.F_PointNum = pointNum;
            model.F_Disabled = disabled.HasValue && disabled.Value ? 1 : 0;
            var result = 0;
            if (kid.HasValue)
            {
                model.Kid = kid.Value;
                result = await ExchangeRuleManager.Update(model);
            }
            else
            {
                result = await ExchangeRuleManager.Add(model);
            }
            switch (result)
            {
                case 0:
                    throw new WebApiException(ExceptionCode.DataError);
                case -1:
                    throw new WebApiException(ExceptionCode.ParameterError, "productKid");
                case -2:
                    throw new WebApiException(ExceptionCode.DataError, "pointNum");
                case -3:
                    throw new WebApiException(ExceptionCode.DataError, "beginTime");
                case -4:
                    throw new WebApiException(ExceptionCode.DataError, "endTime");
                case -5:
                    throw new WebApiException("用户兑换积分不能小于0");
                case -6:
                    throw new WebApiException("每日兑换数量不能小于0");
                case -7:
                    throw new WebApiException("每日兑换开始时间不能为空");
                case -8:
                    throw new WebApiException("每日兑换结束时间不能为空");
                case -9:
                    throw new WebApiException("兑换规则id有误");
                default:
                    break;
            }
            return result;
        }
    }
}
